// pages/transactionRecord/transactionRecord.js
import { getHuankuanData } from '../../api/api';

Page({

  data: {
    detail: {
      aa: 0,
      bb: 0,
      cc: 0
    },
    list: [],
    page: 1,
    limit: 10,
    total: 0,
    hasMore: true
  },

  onLoad(options) {
    // 接收从对账页面传过来的参数
    this.maijiaId = options.maijia_id || '';
    this.storeId = options.store_id || '';
    this.loadData();
  },

  async loadData() {
    try {
      const params = {
        page: this.data.page,
        limit: this.data.limit
      };
      
      // 如果有选中的买家ID，添加到请求参数中
      if (this.maijiaId) {
        params.maijia_id = this.maijiaId;
      }
      
      // 如果有门店ID，添加到请求参数中
      if (this.storeId) {
        params.store_id = this.storeId;
      }
      
      const res = await getHuankuanData(params, { showLoading: true, loadingText: '加载中...' });

      if (res.code === 200 && res.data) {
        const records = res.data.data || [];
        const list = records.map(item => {
          // 计算支付方式
          const paymentMethods = [];
          if (item.cash_num > 0) paymentMethods.push(`已付现金${item.cash_num}元`);
          if (item.wepay_num > 0) paymentMethods.push(`微信${item.wepay_num}元`);
          if (item.alipay_num > 0) paymentMethods.push(`支付宝${item.alipay_num}元`);
          if (item.union_num > 0) paymentMethods.push(`银联${item.union_num}元`);
          if (item.other_num > 0) paymentMethods.push(`其他${item.other_num}元`);

          // 优惠和多收
          const extras = [];
          if (item.youhui > 0) extras.push(`优惠${item.youhui}`);
          if (item.duoshou > 0) extras.push(`多收${item.duoshou}`);

          return {
            maijia_display: item.maijia_name || (item.maijia && item.maijia.name) || item.maijia_id,
            order_count: (item.shouyin_huankuan_record_detail || []).length,
            time: item.add_time,
            payment_text: paymentMethods.join('、'),
            extras_text: extras.join(' '),
            money: item.money,
            userName: item.maijia.username,
            cashier_name: item.user?.name || '',
            zf: item.delete_time ? true : false
          };
        });

        this.setData({
          list: this.data.page === 1 ? list : [...this.data.list, ...list],
          total: res.data.total || 0,
          hasMore: res.data.current_page < res.data.last_page
        });
      }
    } catch (err) {
      console.error('加载还款数据失败', err);
    }
  },

  onReachBottom() {
    if (this.data.hasMore) {
      this.setData({ page: this.data.page + 1 });
      this.loadData();
    }
  },
})
